<template>
  <a-modal
    :title="title"
    :width="1200"
    style="top:10px"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    :okButtonProps="{ props: { disabled: disableSubmit } }"
    cancelText="关闭">
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
<!--        <a-alert v-if="showClosemessage" :message="Closemessage" :type="Clostype" />
        <br v-if="showClosemessage" />-->
        <a-row>
          <a-col :span="12">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="订单号">
              <a-input placeholder="请输入订单号" :disabled="disableSubmit" v-decorator="['orderNumber', {rules: [{required: true, message: '请输入订单号!'},{validator: this.validateOrderNumber}]}]" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item   :labelCol="labelCol" :wrapperCol="wrapperCol" label="订单类型">
              <a-select placeholder="请选择订单类型" :disabled="disableSubmit"  v-decorator="['orderType',{rules: [{required: true, message: '请选择订单状态!'}]}]" @change="setGrabOrder"  style="width: 100%" >
                <a-select-option v-for="item in orderTypes" :key="item.key" :value="item.key">{{ item.val }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="要求">
              <a-input placeholder="请输入要求" :maxLength="100" :disabled="disableSubmit" v-decorator="['demand', {rules: [{required: true, message: '请输入要求!'}]}]" />
            </a-form-item>
          </a-col>
          <a-col :span="12" v-show="showCommission" >
            <a-form-item   :labelCol="labelCol" :wrapperCol="wrapperCol" label="子管理提成比例">
              <a-input-number  style="width: 85%;" :min="0" :disabled="disableSubmit" v-decorator="['commissionRate', {rules: [{required: true, message: '请输入子管理提成比例!'}]}]"  @change="changeMoney"  /><span>(单位:%)</span>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row v-if="showAssign">
          <a-col :span="12">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="子管理">
              <a-input placeholder="请选择子管理"  :readOnly="false" :disabled="disableSubmit" @click="showUserList" v-decorator="['takeManager', {rules: [{required: true, message: '请选择子管理!'}]}]" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="合作用户">
              <a-input placeholder="请选择合作用户" :readOnly="false" :disabled="disableSubmit" @click="showUserListByuser"  v-decorator="['takeOrders', {}]" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row  v-if="!showAssign" >
          <a-col :span="12">
            <a-form-item   :labelCol="labelCol" :wrapperCol="wrapperCol" label="抢单分类">
              <a-select placeholder="请选择订单状态" :disabled="disableSubmit"  v-decorator="['grabType',{rules: [{required: true, message: '请选择抢单分类!'}]}]"   style="width: 100%" >
                <a-select-option v-for="item in grabTypes" :key="item.key" :value="item.key">{{ item.val }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row v-show="showCommission">
          <a-col :span="12" >
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="接单金额">
              <a-input-number  style="width: 85%;" :min="0" :disabled="disableSubmit" placeholder="请输入接单金额"  v-decorator="['takeMoney', {rules: [{required: true, message: '请输入接单金额!'}, {validator: this.validateToCost}]}]" /><span>(单位:元)</span>
            </a-form-item>
          </a-col>
          <a-col :span="12" >
            <a-form-item   :labelCol="labelCol" :wrapperCol="wrapperCol" label="子管理提成数">
              <a-input style="width: 85%;" :readOnly="true"   v-decorator="['takeManagerMoney', {rules: [{required: true, message: '请输入费用!'}]}]" /><span>(单位:元)</span>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="费用">
              <a-input-number  style="width: 85%;" :min="0" :disabled="disableSubmit" placeholder="请输入费用"  @change="changeMoneyByCost" v-decorator="['cost', {rules: [{required: true, message: '请输入费用!'},{validator: this.validateToCost}]}]" /><span>(单位:元)</span>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="要求完成时间">
              <a-date-picker placeholder="请选择要求完成时间"  style="width: 100%;" showTime format='YYYY-MM-DD HH:mm:ss'  :disabled="disableSubmit" v-decorator="[ 'finishTime', {rules: [{required: true, message: '请选择要求完成时间!'}]}]" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :span="12">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="技术要求">
              <a-input placeholder="请输入技术要求"  :maxLength="270" type="textarea" style="height: 80px"  :disabled="disableSubmit" v-decorator="['technical', {}]" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="详细要求">
              <a-input placeholder="请输入详细要求"  type="textarea" style="height: 80px" :disabled="disableSubmit" v-decorator="['requirement', {}]" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12" >
            <a-form-item   :labelCol="labelCol" :wrapperCol="wrapperCol" label="请选择订单状态">
              <a-select placeholder="请选择订单状态" :disabled="disableSubmit"  v-decorator="['orderStatus',{rules: [{required: true, message: '请选择订单状态!'}]}]"   style="width: 100%" >
                <a-select-option v-for="item in orderStatusL" :key="item.key" :value="item.key">{{ item.val }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
            <a-col :span="12" v-show="showclient">
              <a-form-item  :labelCol="labelCol" :wrapperCol="wrapperCol" label="客户信息">
                <a-input placeholder="请输入客户信息" :maxLength="450"  type="textarea" style="height: 80px" :disabled="disableSubmit" v-decorator="['client', {}]" />
              </a-form-item>
            </a-col>
        </a-row>

        <a-row v-if="disableSubmit">
          <a-col :span="12" >
            <a-form-item   :labelCol="labelCol" :wrapperCol="wrapperCol" label="随机码">
              <a-input :readOnly="true"  v-model="code" />
            </a-form-item>
          </a-col>
          <a-col :span="12" >
            <a-form-item   :labelCol="labelCol" :wrapperCol="wrapperCol" label="创建时间">
              <a-date-picker placeholder="请选择创建时间时间"  style="width: 100%;" showTime format='YYYY-MM-DD HH:mm:ss'  :disabled="disableSubmit" v-decorator="[ 'createTime', {}]" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row v-if="disableSubmit" >
          <a-col :span="12" >
            <a-form-item  :labelCol="labelCol" :wrapperCol="wrapperCol"  label="结算截图">
              <img v-if="previewImage" @click="getBigImg" alt="example" style="width: 100px;height: 100px;margin-left: 20%" :src="getAvatarView(previewImage)" />
              <a-alert type="info" show-icon v-else message="未上传结算截图"  />
            </a-form-item>
          </a-col>
        </a-row>
<!--        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="订单状态">
          <a-input-number v-decorator="[ 'orderStatus', {}]" />
        </a-form-item>-->

      </a-form>
      <select-user-list ref="selectUserList" @ok="selectOK"></select-user-list>
      <BigImgModal ref="bigImgModal" ></BigImgModal>
    </a-spin>
  </a-modal>
</template>

<script>
  import Vue from 'vue'
  import {getAction, httpAction} from '@/api/manage'
  import pick from 'lodash.pick'
  import moment from "moment"
  import {randomString} from '@/utils/util'
  import {Dict}   from '@/api/Dict'
  import SelectUserList from "@comp/jeecgbiz/SelectUserList";
  import BigImgModal from "@comp/tools/BigImgModal";
  import { getsysConfig,checkOrderNumber } from '@/api/api';

  export default {
    name: "OrderFormModal",
    components: {SelectUserList,BigImgModal},
    mixins:[Dict],
    data () {
      return {
        title:"操作",
        visible: false,
        model: {},
        previewImage:'',
        //takeManagerMoney:0,//金额数
        showAssign:true,//是否显示指派人
        showCommission:false,//是否显示子管理的提成金额。
        showclient:true,//是否显示客户信息
        disableSubmit:false,
        showClosemessage:false,
        Closemessage:'正常结算',
        Clostype:'warning',
        Rate:'',//管理的提成比例默认值
        code:'0',
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        form: this.$form.createForm(this),
        validatorRules:{
        },
        url: {
          imgerver: window._CONFIG['domianURL'] + "/sys/common/view",
          add: "/orderForm/orderForm/add",
          edit: "/orderForm/orderForm/edit",
          getTakeManagerMoney:"/orderForm/orderForm/getTakeManagerMoney",
        },
      }
    },
    created () {
      this.getsysConfigRate();
    },
    methods: {
      validateOrderNumber(rule, value, callback){
        var params = {
          id:this.model.id,
          orderNumber:value
        };
        checkOrderNumber(params).then((res)=>{
          if(res.success){
            callback();
          }else{
            callback("订单号已存在！");
          }
        });
      },
      validateToCost(rule, value, callback){
        const form = this.form;
        let takeMoney=form.getFieldValue('takeMoney')?Number(form.getFieldValue('takeMoney')):0;
        let cost=form.getFieldValue('cost')?Number(form.getFieldValue('cost')):0;
        console.log("takeMoney-->",takeMoney);
        console.log("cost-->",cost);
        if (takeMoney > cost) {
          callback();
        }else {
          callback("接单费用不能小于或等于费用！");
        }
      },
      getBigImg(){
        this.$refs.bigImgModal.setImage(this.previewImage);
        this.$refs.bigImgModal.previewVisible=true;
      },
      getAvatarView: function (avatar) {
        return this.url.imgerver + "/" + avatar;
      },
      setGrabOrder(val){
        if(val==0){
          this.showAssign=true;
          this.form.setFieldsValue({orderStatus:0});
        }else {
          this.showAssign=false;
          this.form.setFieldsValue({orderStatus:6});
        }
      },
      showUserListByuser(){
      let takeManager=  this.form.getFieldValue('takeManager');
        if(takeManager){
          this.$refs.selectUserList.title = "选择合作用户";
          this.$refs.selectUserList.userRole='visitor';
          this.$refs.selectUserList.userRoleCode=takeManager;
          this.$refs.selectUserList.loadData();
          this.$refs.selectUserList.visible=true;
        }else {
          this.$message.warning('请先选择子管理用户！');
        }
      },
      showUserList(){
        this.$refs.selectUserList.title = "选择子管理用户";
        this.$refs.selectUserList.userRole='manager';
        this.$refs.selectUserList.loadData();
        this.$refs.selectUserList.visible=true;
      },
      selectOK(obj,userRole){
        this.$nextTick(() => {
          if(userRole=='manager'){
            this.form.setFieldsValue({takeManager:obj.username});
          }else {
            this.form.setFieldsValue({takeOrders:obj.username});
          }
        });
      },
      changeMoneyByCost(val){
        this.setTakeManagerMoney(val,this.form.getFieldValue('commissionRate'));
      },
      changeMoney(val){
        this.setTakeManagerMoney(this.form.getFieldValue('cost'),val);
      },
      setTakeManagerMoney(cost,commissionRate){
        console.log("coat-->",cost!=null);
        if(!cost){
          this.form.setFieldsValue({takeManagerMoney:0});
          return 0;
        }
        if(!commissionRate){
          this.form.setFieldsValue({takeManagerMoney:0});
          return 0;
        }
        let that= this;
        getAction(this.url.getTakeManagerMoney, {cost:cost,commissionRate:commissionRate}).then((res)=>{
          if(res.success){
            this.form.setFieldsValue({takeManagerMoney:res.result.takeManagerMoney});
          }else {
            that.$message.warning(res.message);
          }
        });
      },
      getsysConfigRate(){
        let that= this;
        getsysConfig({configKey:'commissionRate'}).then((res)=>{
          if(res.success){
            console.log("res-->",res);
            that.Rate=Number(res.result.records[0].configVal);
          }
        });
      },
      add () {
        let record={};
        record.orderType=0;
        record.orderStatus=0;
        record.commissionRate=this.Rate?this.Rate:10;
        this.edit(record);
      },
      edit (record) {
        let  random= randomString(8);
        this.code=random;
        Vue.ls.set("orderCode"+this.model.id,random);
        let userInfo =  this.$store.getters.userInfo;
        this.setGrabOrder(record.orderType);
        this.form.resetFields();
        this.model = Object.assign({}, record);
        this.visible = true;
        this.previewImage=record.closeImg;
        /*setTimeout(function (){
        },2000);*/
        this.$nextTick(() => {
            this.form.setFieldsValue(pick(this.model,'demand','requirement','technical','cost','takeManager','takeManagerMoney',
              'orderStatus','client','takeMoney','orderType','commissionRate','orderNumber','grabType',
              'createTime','takeOrders'));
            //时间格式化
            this.form.setFieldsValue({finishTime:this.model.finishTime?moment(this.model.finishTime):null})
            if(this.disableSubmit){
              this.form.setFieldsValue({createTime:this.model.createTime?moment(this.model.createTime):null})
            }
            if(userInfo.rolestr=="admin" || userInfo.rolestr=="regulator" || userInfo.rolestr=='accounts' || record.takeOrders==userInfo.username){
              this.showclient=true;
            }else {
              this.showclient=false;
            }
            //是否显示子管理的提成金额
            if(userInfo.rolestr=='admin' || userInfo.rolestr=='regulator' || userInfo.rolestr=='accounts'){
              this.showCommission=true;
              //this.setTakeManagerMoney(record.cost,record.commissionRate);
            }
            //是否显示加价
            /* console.log("orderStatus-->",record.orderStatus);
               if(record.orderStatus==3){
                 this.showClosemessage=true;
                 let Numbers= Number(record.raiseNumber)+Number(record.cost);
                 this.Closemessage='正常结算:加价'+record.raiseNumber+"元,结算"+Numbers+"元";
                 this.Clostype='success';
               }
               if(record.orderStatus==6){
                 this.showClosemessage=true;
                 let Numbers= Number(record.raiseNumber)+Number(record.cost)-50;
                 this.Closemessage='逾期结算:加价'+record.raiseNumber+"元,预期-"+50+"元,结算"+Numbers+"元";
                 this.Clostype='success';
               }*/
          });
      },
      close () {
        this.$emit('ok');
        this.visible = false;
      },
      handleOk () {
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          console.log("err-->",err);
          console.log("values-->",values);
          if (!err) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            let formData = Object.assign(this.model, values);
            //时间格式化
            formData.finishTime = formData.finishTime?formData.finishTime.format('YYYY-MM-DD HH:mm:ss'):null;
            //formData.createTime = formData.createTime?formData.createTime.format('YYYY-MM-DD HH:mm:ss'):null;
            if(formData.orderType==1){
              formData.takeManager=null;
              formData.takeOrders=null;
            }else {
              formData.grabTime=moment(new Date().getTime()).format('YYYY-MM-DD HH:mm:ss');
            }
            if(formData.orderType==0 && !formData.takeOrders){
              formData.takeOrders=formData.takeManager;
            }

              console.log(formData)
            httpAction(httpurl,formData,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
              that.close();
            })

          }
        })
      },
      handleCancel () {
        this.close()
      },


    }
  }
</script>

<style scoped>

</style>